/**
 *  Copyright 2002 Quaseem
 *  Copyright 2004 Migisan
 *  Copyright 2008 Oest
 *  
 *
 *  This file is part of the aochat package.
 *
 *  The aochat package is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  The aochat package is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with the aochat package; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */

package sk.sigp.aobot.client.core;

import java.io.*;
import java.net.Socket;

import sk.sigp.aobot.client.BotCore;
import sk.sigp.aobot.client.core.message.general.Message;

public class MessageHandler implements Runnable {
	
	protected String myhost;
	protected int myport;
	protected BotCore listener;
	protected Socket mySocket;
	protected DataInputStream input;
	protected DataOutputStream output;
	protected Thread myThread;
	protected boolean connected = false;

	public MessageHandler(String host, int port, BotCore bot) {
		myhost = host;
		myport = port;
		listener = bot;
	}

	public void connect() throws IOException {
		mySocket = new Socket(myhost, myport);
		input = new DataInputStream(new BufferedInputStream(mySocket
				.getInputStream()));
		output = new DataOutputStream(new BufferedOutputStream(mySocket
				.getOutputStream()));
		myThread = new Thread(this);
		myThread.start();
		connected = true;
	}

	public boolean connected() {
		return (input != null && output != null && connected);
	}

	public synchronized void send(Message m) throws IOException {
		try {
			m.write(output);
		} catch (UnsupportedEncodingException e) {
			System.out.println(e);
		}
	}

	public void run() {
		try {
			while (true) {
				// First short int (two bytes) is id of command.
				int messageType = -1;
				try {
					messageType = input.readShort();
				} catch (Exception e) {
					e.printStackTrace();
				}
				// Second is length of message.
				int length = input.readShort();

				Message thisMessage = new Message(messageType, input, length);

				listener.messageRecieved(thisMessage);
			}
		} catch (Exception e) {
//			e.printStackTrace();
//			System.out.println(e);
			connected = false;
		}
	}
}
